<template>
  <div class="automation-files">
    <!-- 路径配置区域 -->
    <el-card class="mb-4">
      <template #header>
        <span>文件路径配置</span>
      </template>
      <el-form :model="pathForm" inline>
        <el-form-item label="文件路径">
          <el-select
            v-model="pathForm.filePath"
            placeholder="请选择或输入文件路径"
            style="width: 400px"
            filterable
            allow-create
            clearable
            :loading="configLoading"
          >
            <el-option
              v-for="path in pathOptions"
              :key="path.value"
              :label="path.label"
              :value="path.value"
            >
              <div>
                <div class="flex items-center justify-between w-full">
                   <span>{{ path.label }}</span>
                   <el-tag 
                      v-if="path.type === 'config'" 
                      size="small" 
                      :type="path.fileType === 'score' ? 'warning' : 'primary'" 
                      class="ml-2"
                    >
                      {{ path.fileType === 'score' ? '比分' : '首页' }}
                    </el-tag>
                 </div>
                 <div class="text-sm text-gray-500">{{ path.value }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="pathForm.recursive" label="递归查看" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="pathForm.showHidden" label="显示隐藏文件" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadFiles" :loading="loading">
            <el-icon><Search /></el-icon>
            查看文件
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文件列表区域 -->
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>文件列表</span>
          <div v-if="fileData">
            <el-tag>总计: {{ fileData.totalCount }} 项</el-tag>
          </div>
        </div>
      </template>

      <!-- 当前路径显示 -->
      <div v-if="fileData" class="mb-4">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-icon><Folder /></el-icon>
            {{ fileData.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
        <div class="text-sm text-gray-500 mt-1">
          路径: {{ fileData.path }}
        </div>
        <div class="text-sm text-gray-500">
          修改时间: {{ formatTime(fileData.modifiedTime) }}
        </div>
      </div>

      <!-- 文件表格 -->
      <el-table
        :data="fileData?.items || []"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column label="名称" min-width="300">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-icon class="mr-2" :color="row.isDirectory ? '#409EFF' : '#909399'">
                <Folder v-if="row.isDirectory" />
                <Document v-else />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isDirectory ? 'primary' : 'info'" size="small">
              {{ row.isDirectory ? '目录' : '文件' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            <span v-if="!row.isDirectory">{{ formatFileSize(row.size) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="修改时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.modifiedTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="完整路径" min-width="300">
          <template #default="{ row }">
            <el-text class="text-xs" type="info">{{ row.path }}</el-text>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.isDirectory"
              type="primary"
              size="small"
              @click="navigateToDirectory(row.path)"
            >
              进入
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && (!fileData || !fileData.items.length)"
        description="暂无文件数据"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Search, Folder, Document } from "@element-plus/icons-vue";
import { 
  viewFiles, 
  getImportConfigs,
  type ViewFilesParams, 
  type FileListData,
  type ImportConfig 
} from "@/api/automation";
import { formatTime } from "@/utils/formatTime";
// 移除AutomationNav导入，现在由父页面统一管理

defineOptions({
  name: "AutomationFiles"
});

// 响应式数据
const loading = ref(false);
const configLoading = ref(false);
const fileData = ref<FileListData | null>(null);
const configList = ref<ImportConfig[]>([]);

// 路径选项（基础路径 + 配置路径）
const pathOptions = ref<Array<{ label: string; value: string; type: 'basic' | 'config'; fileType?: 'score' | 'homepage' }>>([]);

// 移除基础路径选项，只使用配置路径

// 路径表单
const pathForm = reactive<ViewFilesParams>({
  filePath: "",
  recursive: false,
  showHidden: false
});

/**
 * 格式化文件大小
 * @param size 文件大小（字节）
 * @returns 格式化后的文件大小字符串
 */
const formatFileSize = (size?: number): string => {
  if (!size) return "-";
  
  const units = ["B", "KB", "MB", "GB", "TB"];
  let index = 0;
  let fileSize = size;
  
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }
  
  return `${fileSize.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
};

/**
 * 加载文件列表
 */
const loadFiles = async () => {
  if (!pathForm.filePath.trim()) {
    ElMessage.warning("请输入文件路径");
    return;
  }
  
  loading.value = true;
  try {
    const response = await viewFiles(pathForm);
    if (response.code === 0) {
      fileData.value = response.data;
      ElMessage.success("文件列表加载成功");
    } else {
      ElMessage.error(response.message || "加载文件列表失败");
    }
  } catch (error) {
    console.error("加载文件列表失败:", error);
    ElMessage.error("加载文件列表失败，请检查网络连接");
  } finally {
    loading.value = false;
  }
};

/**
 * 获取导入配置列表
 */
const loadImportConfigs = async () => {
  configLoading.value = true;
  try {
    const response = await getImportConfigs();
    if (response.code === 0) {
      configList.value = response.data;
      initPathOptions();
    } else {
      console.warn("获取导入配置失败:", response.message);
    }
  } catch (error) {
    console.error("获取导入配置失败:", error);
  } finally {
    configLoading.value = false;
  }
};

/**
 * 初始化路径选项
 */
const initPathOptions = () => {
  // 只使用配置路径，不包含基础路径
  pathOptions.value = configList.value.map(config => ({
     label: `${config.name} (${config.description || '导入配置'})`,
     value: config.importPath,
     type: 'config' as const,
     fileType: config.fileType || 'homepage'
   }));
};

/**
 * 导航到指定目录
 * @param dirPath 目录路径
 */
const navigateToDirectory = (dirPath: string) => {
  pathForm.filePath = dirPath;
  loadFiles();
};

// 组件挂载时初始化
onMounted(async () => {
  // 先初始化路径选项
  initPathOptions();
  // 加载导入配置
  await loadImportConfigs();
  // 不自动加载文件，等用户选择路径后手动加载
});
</script>

<style scoped>
.automation-files {
  padding: 20px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.mr-2 {
  margin-right: 8px;
}

.ml-2 {
  margin-left: 8px;
}

.mt-1 {
  margin-top: 4px;
}

.text-sm {
  font-size: 14px;
}

.text-xs {
  font-size: 12px;
}

.text-gray-500 {
  color: #6b7280;
}
</style>